<?php
/**
 * Create by PhpStorm
 * User: lijia
 * Data: 2020/8/10
 * Time: 10:52
 */

namespace app\api\business;


use app\api\controller\UserCommon;
use app\api\model\Goods;
use think\facade\Db;

class SearchBus extends UserCommon
{

    /**
     * 添加话题搜索
     */
    public function addSearch($keywords){
        $check = Db::name('search')->where('keywords', $keywords)->where('user_id',$this->user_id)->find();
        if ($check){
            Db::name('search')->where('id', $check['id'])->delete();
        }
        $data = [
            'user_id' => $this->user_id,
            'keywords' => $keywords,
            'type' => 1,
            'create_time' => toDate(time())
        ];
        Db::name('search')->insert($data);
    }

    /**
     * 获取话题搜索记录
     */
    public function getTopicList(){
        return Db::name('search')->where('type', 1)->where('user_id', $this->user_id)->select();
    }

    /**
     * 搜索
     * @param $keywords // 搜索关键字
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function searchList($keywords){
        $this->toHistory($keywords);
        $where[] = ['status','=',1];
        $where[] = ['title', 'like', "%" . $keywords . "%"];
        $list = (new Goods())->where($where)->field('id,cover,title,origin_price,present_price,deposit_price')->select();
        return $list;
    }

    /**
     * 保存搜索历史
     */
    public function toHistory($keywords){
        $where = [
            'user_id' => $this->user_id,
            'keywords' => $keywords
        ];
        $history = Db::name('search')->where($where)->find();
        if ($history){
            Db::name('search')->where('id',$history['id'])->update(['create_time'=>time()]);
        }else{
            $data = [
                'user_id' => $this->user_id,
                'keywords' => $keywords,
                'type' => 2,
                'create_time' => toDate(time()),
            ];
            Db::name('search')->insert($data);
        }
    }

    /**
     * 我的搜索历史
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getHistory(){
        return Db::name('search')->where('user_id',$this->user_id)->where('type',2)->field('keywords,create_time')->order('create_time','desc')->select();
    }

    /**
     * 清空搜索
     * @throws \think\db\exception\DbException
     */
    public function clear($type){
        Db::name('search')->where('user_id',$this->user_id)->where('type',$type)->delete();
    }


}